package com.lemon.smartsafety.ui.activity.fire.item.inspection;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.entity.RefreshViewEntity;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingVo;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.fire.SuperviseCompanyResult;
import com.lemon.smartsafetynew.ui.activity.base.NewBaseSearchActivity;
import com.lemon.smartsafety.ui.activity.fire.FirefightingUtil;
import com.lemon.smartsafety.ui.adapter.fire.FireInspectionMainAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.view.ViewFireCompanyNone;
import com.lemon.smartsafety.view.list.ListRefreshView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

public class FireInspectionMainActivity extends NewBaseSearchActivity {

    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.txt_title)
    TextView txtTitle;
    @Bind(R.id.lineAll)
    LinearLayout lineAll;
    @Bind(R.id.listView)
    ListRefreshView listView;
    @Bind(R.id.swipe_layout)
    SwipeRefreshLayout swipeLayout;
    @Bind(R.id.viewFireCompanyNone)
    ViewFireCompanyNone viewFireCompanyNone;


    private SuperviseCompanyResult.ResultEntity resultEntity;

    private FireInspectionMainAdapter fireInspectionMainAdapter;
    private List<CompanyBuildingVo> mList;
    private List<CompanyBuildingVo> companyBuildingVoList;
    private CompanyBuildingVo mCompanyBuildingVo;
    private String strSearch = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getSearchHintRes() {
        return R.string.search_common_hit;
    }

    @Override
    protected void getSearchText(String content) {
        strSearch = content;
        initList();
    }


    @Override
    protected void getBundleArgs() {
        if (getIntent().getExtras() != null) {
            resultEntity = (SuperviseCompanyResult.ResultEntity) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_BASE_INFO);
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_fire_inspection_main;
    }

    @Override
    protected void initTitleView() {
        setBarTitle("企业建筑");
    }

    @Override
    protected void initView() {

        FirefightingUtil.fireInspectAdd(this);
        txtTitle.setText(resultEntity.getCompanyName());

        companyBuildingVoList = new ArrayList<>();
        mList = new ArrayList<>();
        fireInspectionMainAdapter = new FireInspectionMainAdapter(mActivity, mList);
        listView.setAdapter(fireInspectionMainAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                intent = new Intent(mActivity, FireInspectionBuildItemActivity.class);
                bundle = new Bundle();
                bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, resultEntity);
                bundle.putSerializable(BundleKey.COMPANY_BUILD_INFO, mList.get(position));
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });
        initSwipRefresh(swipeLayout);
        initLoadeRefresh(listView);
    }

    @Override
    protected void initHttp() {
        initList();
    }

    @Override
    protected void initList() {
        listView.setIsload(true);
        current_page = 1;
        httpList();
    }

    @Override
    protected void loadList() {
        if (mList.size() % page_size == 0) {
            current_page = current_page + 1;
            httpList();
        } else {
            showUpLoad(false, listView);
            listView.setIsload(false);
            ToastUtil.show("没有更多数据了");
        }
    }

    @Override
    protected void refreshView() {

    }

    /**
     * 错误的情况下 刷新
     */
    public void errorView(String title) {

        try {
            if (CommonUtil.listIsEmpty(mList)) {
                viewFireCompanyNone.setVisibility(View.VISIBLE);
                showSwipLayout(swipeLayout,false);
                if (CommonUtil.strIsEmpty(title)) {
                    viewFireCompanyNone.setContent("没有更多数据");
                    viewFireCompanyNone.setSearch("重试");
                } else {
                    viewFireCompanyNone.setContent(title);
                    viewFireCompanyNone.setSearch("重试");
                }
                viewFireCompanyNone.setAllClick(new ViewFireCompanyNone.AllClick() {
                    @Override
                    public void click() {
                        initList();
                    }
                });
            } else {
                viewFireCompanyNone.setVisibility(View.GONE);
                showSwipLayout(swipeLayout,true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void callFinish() {
        mActivity.finish();
    }


    @Subscribe
    public void onEventMainThread(RefreshViewEntity refreshViewEntity) {
        //刷新View
        if (refreshViewEntity.getTAG().equals(FireInspectionAddBuildActivity.class.getName())) {
            LogUtils.LOGE("刷新View");
            initList();
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        setIconEnable(menu, true);
        boolean menuResult = super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_add, menu);
        return menuResult;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_add) {
            //点击了添加
            LogUtils.LOGE("点击了添加");
            intent = new Intent(mActivity, FireInspectionAddBuildActivity.class);
            bundle = new Bundle();
            bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, resultEntity);
            intent.putExtras(bundle);
            startActivity(intent);

        }
        return super.onOptionsItemSelected(item);
    }


    private void httpList() {
        if (!bPutHttp) {
            bPutHttp = true;
            LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
            params.put("page_size", String.valueOf(page_size));
            params.put("current_page", String.valueOf(current_page));

            params.put("company_code", resultEntity.getCompanyCode());
            params.put("key_word", strSearch);


            showLoading("");
            HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_company_building), "", new HttpOkBase.HttpInterface() {
                @Override
                public void callBackFunction(boolean httpClient, String result) {

                    dismissLoading();
                    bPutHttp = false;
                    if (httpClient) {
                        BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                        if (!CommonUtil.objIsEmpty(baseMode)) {
                            if (HttpBack.httpBackError(baseMode)) {

                                try {
                                    companyBuildingVoList = mGson.fromJson(mGson.toJson(baseMode.getResult()), new TypeToken<List<CompanyBuildingVo>>() {
                                    }.getType());
                                    transList();

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } else {
                                errorView(baseMode.getMsg());
                                ToastUtil.show(baseMode.getMsg());
                            }
                            fireInspectionMainAdapter.notifyDataSetChanged();
                        }
                    }else{
                        companyBuildingVoList=null;
                        errorView("网络连接失败");
                    }
                }
            });
        }

    }


    /**
     * 转换list
     */
    private void transList() {
        if (current_page == 1) {
            mList.clear();
        }
        mList.addAll(companyBuildingVoList);

        fireInspectionMainAdapter.notifyDataSetChanged();

        errorView("");
    }


}
